﻿namespace AddressBook.Business.Person
{
	#region "Using Statements"
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Text;

	using Csla;
	using Csla.Data;
	#endregion

	public class StateProvinceList : ReadOnlyListBase<StateProvinceList, StateProvinceInfo>
	{
		#region  "Factory Methods"

    public static StateProvinceList EmptyList()
    {
      return new StateProvinceList();
    }

		public static StateProvinceList GetStateProvinceList()
    {
      return DataPortal.Fetch<StateProvinceList>();
    }

		private StateProvinceList()
    { /* require use of factory methods */ }

    #endregion

		#region  "Data Access"

		private void DataPortal_Fetch()
		{
			RaiseListChangedEvents = false;

			using (var ctx = ContextManager<AddressBook.Business.Model.AddressBookDataContext>.GetManager(AddressBook.Business.Model.Database.AddressBook))
			{
				List<StateProvinceInfo> data = (from sp in ctx.DataContext.StateProvinces
																				where sp.CountryRegionCode.Equals("US")
																				orderby sp.StateProvinceCode
																				select new StateProvinceInfo(sp.Id,
																																		 sp.StateProvinceCode,
																																		 (sp.CountryRegion != null ? sp.CountryRegion.CountryRegionCode : String.Empty),
																																		 sp.Name,
																																		 sp.IsOnlyStateProvinceFlag)
																																 ).ToList<StateProvinceInfo>();

				this.IsReadOnly = false;

				this.AddRange(data);

				this.IsReadOnly = true;
			}

			RaiseListChangedEvents = true;
		}

		#endregion
	}
}
